<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<title></title>
	</head>
	<body>
		<input type="file" name="file" id="file" value="" />
		<dl>
			<dt>压缩步骤：</dt>
			<dd>1.选择图片</dd>
			<dd>2.获取文件，判断格式及大小</dd>
			<dd>3.FileReader转为base64，获取图片的原始宽高</dd>
			<dd>4.计算需要压缩后的图片宽高</dd>
			<dd>5.将图片写入canvas</dd>
			<dd>6.再将canvas 压缩输出图片</dd>
		</dl>
		<script type="text/javascript">
			const input = document.querySelector('#file')
			// 上传的格式类型
			const FILE_TYPES = ['image/png','image/jpg','image/jpeg']
			// 最大上传尺寸 2M
			const MAX_SIZE = 2
			// 图片最大宽
			let MAX_WIDTH=750
			// 图片最大高
			let MAX_HEIGHT=750
			
			input.addEventListener('change',(e)=>{
				// 打开选择框，取消不执行
				if(!e.target.files.length) return false
				
				// 获取文件，判断格式及大小
				const file = e.target.files[0]
				const {size,type} = file
				if(!checkType(type)){
					input.value = ''
					alert("上传的图片格式不正确")
				}
				if(!checkSize(size)){
					input.value = ''
					alert("上传的图片太大了，请调整图片大小")
				}
				// 通过FileReader转为base64图片
				const fileReader = new FileReader()
				fileReader.addEventListener('load',(e)=>{
					const img = new Image()
					img.src = e.target.result // base64
					img.addEventListener('load',(e)=>{
						// 获取图片的原始宽高
						const {naturalWidth,naturalHeight} = img
						// 缩放系数
						let ratio = 1
						// 设置需要压缩后的图片宽高
						if(naturalWidth > MAX_WIDTH){
							ratio = naturalWidth / MAX_WIDTH
							MAX_HEIGHT = naturalHeight / ratio
						}else if(naturalHeight > MAX_HEIGHT){
							ratio = naturalHeight / MAX_HEIGHT
							MAX_HEIGHT = naturalWidth / ratio
						}else{
							MAX_WIDTH = naturalWidth
							MAX_HEIGHT = naturalHeight
						}
						// 将图片转为canvas
						const canvas = convertImageToCanvas(img,MAX_WIDTH,MAX_HEIGHT)
						// 将canvas生成图片
						const convertImage = convertCanvasToImage(canvas,0.9)
						document.querySelector('body').appendChild(convertImage)
						
					})
				})
				fileReader.readAsDataURL(file)
			})
			/**
			 * 将图片转为canvas
			 */
			const convertImageToCanvas = (image,w,h)=>{
				// 创建图片大小的canvas
				const oC = document.createElement('canvas')
				const ctx = oC.getContext('2d');
				oC.setAttribute('width',w,)
				oC.setAttribute('height',h)
				// 绘制图片
				ctx.drawImage(image,0,0,w,h)
				return oC
			}
			/**
			 * 将canvas转为图片
			 */
			const convertCanvasToImage = (canvas,quality=0.75)=>{
				console.log(canvas);
				let img = new Image()
				img.src = canvas.toDataURL('image/jpeg',quality)
				return img
			}
			
			// 检查图片大小
			const checkSize = (size)=>{
				if(size > MAX_SIZE*1024*1024) return false
				return true
			}
			// 检查图片格式
			const checkType = (type)=>{
				if(!FILE_TYPES.includes(type)) {
					return false
				}
				return true
			}
		</script>
	</body>
</html>
